﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Threading.Tasks;

namespace WSCore
{
    public abstract class WSNode
    {
		private long _creationTicks = DateTime.Now.Ticks;

		public string Description { get; set; }

		//数值越小优先级越高
		public virtual int ZOrder { get; set; }

		public virtual float ScaleX { get; set; }

		public virtual float ScaleY { get; set; }

		public virtual float Scale
		{
			set 
			{
				ScaleX = value;
				ScaleY = value;
			}
		}

		public virtual PointF Position { get; set; }

		public virtual float X 
		{
			get { return Position.X; }
			set { Position = new PointF(value, Position.Y); }
		}

		public virtual float Y
		{
			get { return Position.Y; }
			set { Position = new PointF(Position.X, value); }
		}

		public virtual PointF PinPoint { get; set; }

		public virtual SizeF Size { get; set; }

		public virtual bool Visible { get; set; }
		
		//角度，正为顺时针
		public virtual float Rotation { get; set; }

		public virtual float RotationX { get; set; }

		public virtual float RotationY { get; set; }

		public int Tag { get; set; }

		public WSNode Parent { get; set; }

		public List<WSNode> Children { get; set; }

		public int ChildrenCount 
		{ 
			get 
			{
				if (Children != null)
					return Children.Count;
				else
					return 0;
			} 
		}

		public virtual void AddChild(WSNode child)
		{
			if (Children == null)
				Children = new List<WSNode>();

			child.Parent = this;
			Children.Add(child);
		}

		public virtual void RemoveChild(WSNode child)
		{
			if (child != null && Children != null)
			{
				child.Parent = null;
				Children.Remove(child);
			}
		}

		public virtual void RemoveAllChildren()
		{
			if (Children != null)
			{
				foreach (var child in Children)
				{
					child.Parent = null;
				}
			}

			Children.Clear();
		}

		public virtual void RemoveFromParent()
		{
			if (Parent != null)
				Parent.RemoveChild(this);
		}

		public virtual void SortChildren()
		{
			if (Children != null)
			{
				Children.Sort((a, b) => {
					if (a.ZOrder != b.ZOrder)
						return a.ZOrder - b.ZOrder;
					else
					{
						return (int)(a._creationTicks - a._creationTicks);
					}
				});
			}
		}

		public abstract void Render();

		public virtual void Visit()
		{
			if (!Visible)
				return;

			if (Children != null && Children.Count > 0)
			{
				//画Z < 0的
				int i = 0;
				for (; i < Children.Count; i++)
				{
					if (Children[i].ZOrder < 0)
						Children[i].Render();
					else
						break;
				}

				this.Render();

				for (; i < Children.Count; i++)
				{
					Children[i].Render();
				}
			}
			else
			{
				this.Render();
			}
		}
    }
}
